package com.xu.sso.server.controller;

import com.alibaba.fastjson.JSONObject;
import com.xu.sso.core.exception.SSOException;
import com.xu.sso.core.model.BaseResponse;
import com.xu.sso.server.model.request.ApiLoginRequest;
import com.xu.sso.server.model.request.ApiLogoutRequest;
import com.xu.sso.server.model.response.ApiLoginResponse;
import com.xu.sso.server.model.response.LoginResponse;
import com.xu.sso.server.service.LoginService;
import com.xu.sso.server.service.convert.ApiLoginConvert;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

@Slf4j
@RestController
@RequestMapping("/api")
public class LoginApiController extends BaseController {

    @Autowired
    private LoginService loginService;

    @RequestMapping("/login")
    public ApiLoginResponse login(@RequestBody @Valid ApiLoginRequest request, BindingResult bindingResult) throws SSOException {
        log.info(">>>>>>>>>>>>>>>LoginApiController.login request=={}", JSONObject.toJSONString(request));
        validParams(bindingResult);
        LoginResponse loginResponse = loginService.login(ApiLoginConvert.convert(request));
        return ApiLoginConvert.convert(loginResponse);
    }

    @RequestMapping("/logout")
    public BaseResponse logout(@RequestBody @Valid ApiLogoutRequest request, BindingResult bindingResult) throws SSOException {
        log.info(">>>>>>>>>>>>>>>LoginApiController.logout request=={}", JSONObject.toJSONString(request));
        validParams(bindingResult);
        return loginService.logout(request);
    }

}
